package com.mojian.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.mojian.common.Result;
import com.mojian.service.impl.ArticleViewRecordServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 文章浏览记录控制器
 */
@RestController
@RequestMapping("/api/article/view")
@RequiredArgsConstructor
@Api(tags = "文章浏览记录接口")
@Slf4j
public class ArticleViewController {

    private final ArticleViewRecordServiceImpl articleViewRecordService;

    /**
     * 记录文章浏览
     * @param articleId 文章ID
     * @param readTime 阅读时间（秒）
     * @return 操作结果
     */
    @PostMapping("/record")
    @ApiOperation("记录文章浏览")
    public Result<Void> recordArticleView(
            @RequestParam("articleId") Long articleId,
            @RequestParam(value = "readTime", defaultValue = "0") Integer readTime) {
        
        try {
            // 只有登录用户才记录详细浏览数据
            Long userId = 0L; // 默认为游客
            if (StpUtil.isLogin()) {
                userId = StpUtil.getLoginIdAsLong();
                log.info("记录用户[{}]浏览文章[{}], 阅读时间: {}秒", userId, articleId, readTime);
            } else {
                // 未登录用户只更新文章浏览量
                log.info("未登录用户浏览文章[{}]", articleId);
            }
            
            articleViewRecordService.recordArticleView(userId, articleId, readTime);
            return Result.success();
        } catch (Exception e) {
            log.error("记录文章浏览失败", e);
            return Result.error("记录失败");
        }
    }
} 